import React, {Component} from 'react'

const SIZE = 10;
const PAGE_SIZE = 10;

class Page extends Component {
  constructor(props) {
    super(props)

    this.state = {
      // count: props.count,
      total: this.calculateTotal(props.count),
      cur: props.cur,
      pages: []
    }

  }

  onPageClick = (e) => {
    e.preventDefault();
    const cur = parseInt(e.target.dataset.index, 10)
    if(this.state.cur === cur)
      return;
    // console.log('emit Page onPageChange cur:', cur)
    this.props.onPageChange(cur);
  }

  calculateTotal(count) {
    return Math.ceil(count / PAGE_SIZE)
  }

  calculatePages() {
    const pages = [];
    if(this.state.total === 0)
      return pages;

    let total = this.state.total;
    let cur = this.state.cur;
    if(cur < SIZE){
      var end = Math.min(SIZE, total)
      while(end){
        pages.unshift(end--)
      }
    } else {
      let start = cur - Math.floor(SIZE / 2);
      if(start > total - SIZE){
        start = total - SIZE + 1;
      }
      let end = SIZE;
      while(end--){
        pages.push(start++)
      }
    }

    return pages;
  }

  componentDidMount() {
    const pages = this.calculatePages();
    this.setState({pages: pages})

  }

  render() {
    return (
      <div className="pagination">
        <ul data-current="1">
          <li><a onClick={this.onPageClick} data-index="1">首页</a></li>
          <li><a onClick={this.onPageClick} data-index={this.state.cur - 1}>上一页</a></li>
          {this.state.pages.map(page =>(
             <li key={page} className={this.state.cur === page ? 'active':''}>
                <a onClick={this.onPageClick} data-index={page}>{page}</a>
              </li>
          ))}
          <li><a onClick={this.onPageClick} data-index={this.state.cur + 1}>下一页</a></li>
          <li><a onClick={this.onPageClick} data-index={this.state.total}>尾页</a></li>
        </ul>
      </div>
    )
  }
}

export default Page